package com.rdgk.newtech.util;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author hanhuailiang
 * @description
 * @date 2019/8/21 15:32
 **/
public class UploadFileUtil {
    public static JSONObject uploadFile(HttpServletRequest request, MultipartFile file, String uploadPath) {
        JSONObject jsonObject = new JSONObject();
        //用来检测程序运行时间
        long  startTime=System.currentTimeMillis();
        String fileName = file.getOriginalFilename();
        String[] str = fileName.split("\\.");
        String fileType = str[str.length-1];
        //String path = request.getSession().getServletContext().getRealPath("/")+"\\upload\\";
        File filepath=new File(uploadPath);
        //判断文件夹是否存在
        if (!filepath.exists()) {
            filepath.mkdirs();
        }
        try {
            //获取输出流
            OutputStream os=new FileOutputStream(uploadPath+startTime+"."+fileType);
            //获取输入流 CommonsMultipartFile 中可以直接得到文件的流
            InputStream is=file.getInputStream();
            byte[] bts = new byte[1024];
            //一个一个字节的读取并写入
            while(is.read(bts)!=-1){
                os.write(bts);
            }
            os.flush();
            os.close();
            is.close();

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        long  endTime=System.currentTimeMillis();
        System.out.println("采用流上传的方式的运行时间："+String.valueOf(endTime-startTime)+"ms");
        jsonObject.put("filename",fileName);
        jsonObject.put("filepath",uploadPath+startTime+"."+fileType);
        return jsonObject;
    }

}
